from flask import Blueprint, request, jsonify
import hashlib
import json
import mysql.connector
from config import mysql_config

blockchain_bp = Blueprint('blockchain', __name__)

def get_db_connection():
    return mysql.connector.connect(**mysql_config)

# 创建数据存证记录
@blockchain_bp.route('/api/blockchain/records', methods=['POST'])
def create_record():
    try:
        data = request.get_json()
        data_type = data.get('data_type')
        data_content = data.get('data_content')
        
        if not data_type or not data_content:
            return jsonify({'error': '数据类型和内容不能为空'}), 400
            
        # 生成数据哈希
        data_str = json.dumps(data_content, sort_keys=True)
        data_hash = hashlib.sha256(data_str.encode()).hexdigest()
        
        # 模拟区块链交互，生成区块哈希
        block_hash = hashlib.sha256((data_hash + str(datetime.now().timestamp())).encode()).hexdigest()
        
        conn = get_db_connection()
        cursor = conn.cursor(dictionary=True)
        
        # 插入存证记录
        sql = """
        INSERT INTO blockchain_records 
        (data_type, data_content, data_hash, block_hash, created_at) 
        VALUES (%s, %s, %s, %s, %s)
        """
        values = (data_type, json.dumps(data_content), data_hash, block_hash, datetime.now())
        
        cursor.execute(sql, values)
        conn.commit()
        
        record_id = cursor.lastrowid
        
        cursor.close()
        conn.close()
        
        return jsonify({
            'message': '存证记录创建成功',
            'record_id': record_id,
            'data_hash': data_hash,
            'block_hash': block_hash
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

# 获取存证记录列表
# 新增区块链验证逻辑
def validate_chain(record):
    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)
    
    try:
        # 验证前序哈希
        if record['prev_hash'] != 'genesis':
            prev_sql = "SELECT block_hash FROM blockchain_records WHERE record_id = %s"
            cursor.execute(prev_sql, (record['record_id']-1,))
            prev_record = cursor.fetchone()
            if prev_record['block_hash'] != record['prev_hash']:
                return False
        
        # 验证当前哈希
        data_str = json.dumps(record['data_content'], sort_keys=True)
        calculated_hash = hashlib.sha256(f"{data_str}{record['prev_hash']}".encode()).hexdigest()
        return calculated_hash == record['block_hash']
    finally:
        cursor.close()
        conn.close()

# 在现有路由中添加验证逻辑
# 在文件开头添加缺失的datetime导入
from datetime import datetime

# 修复get_records路由的语法错误
@blockchain_bp.route('/api/blockchain/records', methods=['GET'])
def get_records():
    try:
        page = int(request.args.get('page', 1))
        page_size = int(request.args.get('pageSize', 10))
        offset = (page - 1) * page_size
        
        conn = get_db_connection()
        cursor = conn.cursor(dictionary=True)
        
        # 获取总记录数
        cursor.execute("SELECT COUNT(*) as total FROM blockchain_records")
        total = cursor.fetchone()['total']
        
        # 获取分页数据时添加prev_hash字段
        sql = """
        SELECT record_id, data_type, data_hash, prev_hash, block_hash, created_at as timestamp
        FROM blockchain_records 
        ORDER BY created_at DESC 
        LIMIT %s OFFSET %s
        """
        cursor.execute(sql, (page_size, offset))
        records = cursor.fetchall()
        
        # 为每条记录添加验证状态
        for record in records:
            record['chain_valid'] = validate_chain(record)
        
        cursor.close()
        conn.close()
        
        return jsonify({'items': records, 'total': total})
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

# 获取存证记录详情
@blockchain_bp.route('/api/blockchain/records/<int:record_id>', methods=['GET'])
def get_record_detail(record_id):
    try:
        conn = get_db_connection()
        cursor = conn.cursor(dictionary=True)
        
        sql = "SELECT * FROM blockchain_records WHERE record_id = %s"
        cursor.execute(sql, (record_id,))
        record = cursor.fetchone()
        
        cursor.close()
        conn.close()
        
        if not record:
            return jsonify({'error': '记录不存在'}), 404
            
        # 解析JSON格式的数据内容
        record['data_content'] = json.loads(record['data_content'])
        
        return jsonify(record)
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

# 验证数据
@blockchain_bp.route('/api/blockchain/verify', methods=['POST'])
def verify_data():
    try:
        data = request.get_json()
        verify_type = data.get('verify_type')
        data_id = data.get('data_id')
        data_content = data.get('data_content')
        
        if not verify_type or not data_id or not data_content:
            return jsonify({'error': '验证类型、数据ID和内容不能为空'}), 400
            
        # 生成待验证数据的哈希
        data_str = json.dumps(data_content, sort_keys=True)
        verify_hash = hashlib.sha256(data_str.encode()).hexdigest()
        
        conn = get_db_connection()
        cursor = conn.cursor(dictionary=True)
        
        # 查询原始存证记录
        sql = """
        SELECT data_hash, block_hash, created_at as timestamp 
        FROM blockchain_records 
        WHERE record_id = %s AND data_type = %s
        """
        cursor.execute(sql, (data_id, verify_type))
        record = cursor.fetchone()
        
        cursor.close()
        conn.close()
        
        if not record:
            return jsonify({
                'valid': False,
                'error': '未找到对应的存证记录'
            })
            
        # 验证数据哈希是否匹配
        is_valid = verify_hash == record['data_hash']
        
        result = {
            'valid': is_valid,
            'data_hash': verify_hash,
            'block_hash': record['block_hash'],
            'timestamp': record['timestamp'].isoformat()
        }
        
        if not is_valid:
            result['error'] = '数据内容与原始存证不匹配'
            
        return jsonify(result)
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500